const childProcess = require('child_process');

const dayjs = require('dayjs');
const router = require('koa-router')();

const unSuppored = '不支持非Linux系统的脚本调用！'
const uatSSH = `sshpass -p '!QAZxsw23edc' ssh apps_admin@10.164.2.133 `;
const prodSSH = `sshpass -p 'C@pitaland123' ssh apps_admin@10.164.5.160 `;

router.prefix('/api/shell');

router.get('/supported', async (ctx, next) => {
  let rs = {
    at: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    success: true,
    data: {
      internet: false,
      capitalandNet: false,
      platform: process.platform
    }
  };

  try {
    let canAccessInternet = await ctx.httpClient.get('https://www.baidu.com', { timeout: 2000 });

    if (canAccessInternet.body) {
      rs.data.internet = true;
    }
  } catch { }

  try {
    let canAccessCapitaland = await ctx.httpClient.get('http://10.164.2.213:7000/Account/LogIn', { timeout: 2000 });

    if (canAccessCapitaland.body) {
      rs.data.capitalandNet = true;
    }
  } catch { }

  ctx.body = rs;
});

router.get('/process', async (ctx, next) => {
  let rs = {
    at: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    success: true
  };

  if (!isSupported()) {
    rs.success = false;
    rs.message = unSuppored;

    await (ctx.body = rs);

    return;
  }

  let type = ctx.request.query.type;
  let prefix = '';

  if (type == 'uat') {
    prefix = uatSSH;
  } else if (type == 'prod') {
    prefix = prodSSH;
  }

  childProcess.execSync(`${prefix}//usr/bin/top -d 2 -n 1 -b > /root/process.log;`);

  let data = childProcess.execSync('cat /root/process.log;');

  rs.datas = data.toString('utf8').split('\n').filter(d => !!d);

  await (ctx.body = rs);
});

router.post('/exec', async (ctx, next) => {
  let rs = {
    at: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    success: true
  };

  if (!isSupported()) {
    rs.success = false;
    rs.message = unSuppored;

    await (ctx.body = rs);

    return;
  }

  let command = ctx.request.body.command;
  let data = childProcess.execSync(command);

  rs.datas = data.toString('utf8').split('\n').filter(d => !!d);

  await (ctx.body = rs);
});

function isSupported () {
  return process.platform == 'linux';
}

module.exports = router;